package com.lujieni.springbootwebsocket.service;

import com.alibaba.fastjson.JSON;
import com.lujieni.springbootwebsocket.dto.WebsiteMsgDTO;
import com.lujieni.springbootwebsocket.server.WebSocketServer;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.io.IOException;

/**
 * @author
 * @Title: ConsumePersonService
 * @Description:
 * @date 2022/6/21 9:55 下午
 */
@Service
public class WebsiteMsgReceiver {
    @Autowired
    private WebSocketServer webSocketServer;

    private Jackson2JsonMessageConverter jackson2JsonMessageConverter;

    public WebsiteMsgReceiver() {
        this.jackson2JsonMessageConverter = new Jackson2JsonMessageConverter();
    }

    //@RabbitListener(queues = "delivery.trace.queue") //直接绑定mq中queue的列名
    @RabbitListener(queues = "#{createWebsocketQueue}") //直接绑定类型为Queue,beanName为createWebsocketQueue的对象
    public void show(Message message, Channel channel) throws IOException {
        try {
            WebsiteMsgDTO dto = JSON.parseObject(new String(message.getBody()), WebsiteMsgDTO.class);


            String msg = dto.getMsg();
            String userCode = dto.getUserCode();

            Session session = webSocketServer.checkIsOnline(userCode);
            if(session != null){
                System.out.println("session存在本服务器上");
                webSocketServer.sendMessageToSpecificClient(msg, session);
            }else{
                System.out.println("session不存在本服务器上,跳过");
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); //直接ack
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }
    }

}
